<script setup>
import { storeToRefs } from 'pinia';
import useDataStore from '../../store';
import { onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
import { getLeaveMessageAPI, postLeaveMessageAPI } from '../../apis/chat';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css'
import { DomEditor } from '@wangeditor/editor'
import { sfm, nyr } from '../../utils/tool';
import { useRoute } from 'vue-router';
import meHeader from '../me/components/meHeader.vue';


defineOptions({
    name: 'messageBoard'
})

const route = useRoute()
const dataStore = useDataStore()
const { userInfo, isMobile } = storeToRefs(dataStore)


let leaveMessageList = ref([])  //留言列表
let isMe = ref(route.query.user_id ? false : true)  // 是否当前用户的留言板
let currentTime = ref(new Date())   // 留言时间
let calendarRef = ref() //日历实例

const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef
let valueHtml = ref('')   // 内容html
//工具栏配置项
const toolbarConfig = {
    excludeKeys: [
        'uploadImage',
        'uploadVideo',
        'fullScreen',
        'codeBlock',
        'todo',
        'insertImage',
        'insertLink',
        'insertTable',
        'viewImageLink',
        'insertVideo',
        'blockquote',
        'numberedList',
        'group-image',
        'group-video'
    ]

}
const editorConfig = { placeholder: '在这里输入留言内容...' }   // 编辑器配置项

onMounted(() => {
    getLeaveMessage()
})

// 日历时间改变
const changeDate = (val) => {
    console.log('val', val, currentTime.value, calendarRef.selectedDay);
    if (!calendarRef.value) return

    calendarRef.value.selectDate(val)


    // getLeaveMessage(currentTime.value)
}

/* -------------------------------- 创建富文本编辑器 -------------------------------- */
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor
    // const toolbar = DomEditor.getToolbar(editorRef.value)
    // console.log(editorRef.value);
    // console.log(editorRef.value.getConfig().MENU_CONF);
}

// 获取留言信息
const getLeaveMessage = async (time) => {
    let timeStr
    if (time) {
        timeStr = nyr(time, '-')
    }
    let res = await getLeaveMessageAPI(route.query.user_id || userInfo.value.user_id, timeStr)
    if (res.code === 200) {
        leaveMessageList.value = res.data
    } else {
        leaveMessageList.value = []
    }
}

// 点击留言
const leavingAction = async () => {
    console.log('value', valueHtml.value);
    if (valueHtml.value) {
        let res = await postLeaveMessageAPI(valueHtml.value, userInfo.value.user_id, route.query.user_id)
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '留言成功'
            })
            valueHtml.value = ''
            getLeaveMessage()
        }
    } else {
        ElMessage({
            type: 'warning',
            message: '输入内容不能为空'
        })
    }
}

// 点击清空
const clearAction = () => {
    valueHtml.value = ''
}

//点击所有
const allAction = () => {
    getLeaveMessage()
}

watch(
    () => currentTime.value,
    (newVal, oldVal) => {
        getLeaveMessage(newVal)
    }
)


</script>

<template>
    <div class="page">
        <div class="container">
            <div class="headers" :style="{ transform: meHeaderFlag ? 'translateY(0px)' : 'translateY(0px)' }">
                <meHeader>
                </meHeader>
            </div>
            <div class="temp" v-show="!isMobile"></div>
            <div class="main">
                <div class="leftbox"></div>
                <div class="left">
                    <div class="left-now">
                        <div class="now-date">{{ nyr(currentTime) }}</div>
                        <!-- <div class="now-time">{{ sfm(new Date(currentTime)) }}</div> -->
                    </div>
                    <div class="left-calendar">
                        <el-calendar v-model="currentTime" ref="calendarRef">
                            <template #header="{ data }">
                                <el-button-group class="calendar-btns">
                                    <el-button size="small" @click="changeDate('prev-year')">
                                        << </el-button>
                                            <el-button size="small" @click="changeDate('prev-month')">
                                                < </el-button>
                                                    <el-button size="small" @click="changeDate('today')">●</el-button>
                                                    <el-button size="small" @click="changeDate('next-month')">
                                                        >
                                                    </el-button>
                                                    <el-button size="small" @click="changeDate('next-year')">
                                                        >>
                                                    </el-button>
                                </el-button-group>
                                <el-button size="small" @click="allAction">所有</el-button>
                            </template>
                            <template #date-cell="{ data }">
                                <p :class="data.isSelected ? 'is-selected' : ''">
                                    {{ data.day.split('-').slice(2).join('-') }}
                                    {{ data.isSelected ? '✔️' : '' }}
                                </p>
                            </template>
                        </el-calendar>
                    </div>
                </div>
                <div class="right">
                    <!-- <div class="right-welcome"></div> -->
                    <div class="right-leaving" id="editor—wrapper1" v-if="!isMe">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" />
                        <Editor style="height: 100px; overflow-y: hidden;" v-model="valueHtml"
                            :defaultConfig="editorConfig" @onCreated="handleCreated" />
                        <div class="leaving-btn">
                            <el-button @click="leavingAction">留言</el-button>
                            <el-button @click="clearAction">清空</el-button>
                        </div>

                    </div>
                    <div class="right-content">
                        <div class="content-title">留言板（{{ leaveMessageList.length }}）</div>
                        <div class="content-item" v-for="(item, index) in leaveMessageList" :key="item.leave_id">
                            <div class="item-top">
                                <div class="top-avatar"><img :src="item.user_avatar" alt=""></div>
                                <div class="top-info">
                                    <div class="info-name">{{ item.user_name }}</div>
                                    <div class="info-email">{{ item.user_email }}</div>
                                </div>
                                <div class="top-time">
                                    <div class="time-floor">{{ leaveMessageList.length - index }}楼</div>
                                    <div class="time">{{ item.leave_time }}</div>
                                </div>
                            </div>
                            <div class="item-mid" v-html="item.leave_content"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped lang='scss'>
@import url(./messageBoard.scss);
</style>